#!/usr/bin/python
# -*- coding: utf-8 -*-

#为方便以后移植，参数中的 key 一律为字符串格式
import logging
from google.appengine.ext import db
from google.appengine.api import memcache 
from google.appengine.api import users

import googledatabase
import getcounter
import commonfunction
import databasefunction

LIKE_ID_COUNT_NAME = 'LikeIDCount'


#===================================== 朋友 =============================================

#检查一个自己的朋友的记录
def GetOneMyFriend(FriendLoginName):
    LoginName = commonfunction.GetUserLoginName()
#    logging.error("-------GetOneMyFriend FriendName = %s, UserLoginName = %s " % (FriendLoginName, LoginName) )
    if 1 > len(FriendLoginName) or 1 > len(LoginName):
        return None

    Query = db.GqlQuery('SELECT * FROM CFriendTable WHERE FriendName = :1 AND LoginName = :2', FriendLoginName, LoginName)
    return Query.get()

#检查一个用户的朋友的记录
def GetOneUserFriend(FriendLoginName, UserLoginName):
#    logging.error("-------GetOneUserFriend FriendLoginName = %s, UserLoginName = %s " % (FriendLoginName, UserLoginName) )
    if 1 > len(FriendLoginName) or 1 > len(UserLoginName):
        return None

    Query = db.GqlQuery('SELECT * FROM CFriendTable WHERE FriendName = :1 AND LoginName = :2', FriendLoginName, UserLoginName)
    return Query.get()


#分页、逆时获得某用户指定状态朋友的记录集（函数内转换了朋友的昵称）
#返回： 结果集, 前一页起始TagID, 后一页起始TagID
def GetOneUserFriendRecord(UserLoginName, ResponsionState, PageSize, TimeDelta, TagDate = '', ModifyNickName = True):
#    logging.debug( "-------------- FriendRecord 1: UserLoginName = %s, ResponsionState = %d, TimeDelta = %s, TagDate = %s, ModifyNickName = %d"
#                   % (UserLoginName, ResponsionState, TimeDelta, TagDate, ModifyNickName) )
    #计算上一页起始ID
    PrePageTag = ''
    if 0 < len(TagDate):
        Query = db.GqlQuery( 'SELECT * FROM CFriendTable WHERE LoginName = :1 AND ResponsionState = :2 AND Date > :3 ORDER BY Date',
                             UserLoginName, ResponsionState, commonfunction.GetDatetimeFromString(TagDate) )
        Results = Query.fetch(PageSize)
        if Results:
            PrePageTag = str(Results[len(Results) - 1].Date)
#    logging.debug( "--------------------- FriendRecord 2: TagDate = %s, PrePageTag = %s" % (TagDate, PrePageTag) )
            
    #计算下一页起始ID
    Query = db.GqlQuery( 'SELECT * FROM CFriendTable WHERE LoginName = :1 AND ResponsionState = :2 ORDER BY Date DESC', UserLoginName, ResponsionState )
    if 0 < len(TagDate):
        Query = db.GqlQuery( 'SELECT * FROM CFriendTable WHERE LoginName = :1 AND ResponsionState = :2 AND Date <= :2 ORDER BY Date DESC',
                             UserLoginName, ResponsionState, commonfunction.GetDatetimeFromString(TagDate) )
    Results = Query.fetch(PageSize + 1)
#    logging.debug( "--------------------- FriendRecord 3: len(Results) = %d" % (len(Results)) )
    
    NextPageTag = ''
    if len(Results) == PageSize + 1:
        NextPageTag = str(Results[PageSize].Date)
        Results = Results[:PageSize]

    #修正用户昵称
    for Item in Results:
        if ModifyNickName:
            Item.FriendName = commonfunction.GetOneUserNickName(Item.FriendName)
            if '' == Item.FriendName:
                Item.FriendName = commonfunction.GetEmptyNickName(TimeDelta)
                
        Item.Date += TimeDelta

    return Results, PrePageTag, NextPageTag


#分页、逆时获得某用户指定状态朋友的基本信息集，内部已对 NickName做了处理，调用者显示时可以方便的只使用 NickName
#返回： 结果集, 前一页起始TagID, 后一页起始TagID
def GetOneUserFriendBaseInfoList(UserLoginName, ResponsionState, PageSize, TimeDelta, TagDate = ''):
    Friends, PrePageTag, NextPageTag = GetOneUserFriendRecord(UserLoginName, ResponsionState, PageSize, TimeDelta, TagDate, False)
#    logging.error( "--------------------- GetOneUserFriendBaseInfoList 1: Friends number = %d" % (len(Friends)) )

    FreindInfos = []
    for Item in Friends:
        OneUserInfo = databasefunction.GetOneUserInfo(Item.FriendName)
        if OneUserInfo:
            OneBaseInfo = googledatabase.CUserBaseInfo()
            OneBaseInfo.UserKeyString = str(OneUserInfo.key())
            OneBaseInfo.LoginName = OneUserInfo.LoginName
            OneBaseInfo.LoginEmail = OneUserInfo.LoginEmail
            OneBaseInfo.LoginID = OneUserInfo.LoginID
            OneBaseInfo.NickName = OneUserInfo.NickName
            if '' == OneBaseInfo.NickName:
                OneBaseInfo.NickName = OneBaseInfo.LoginName
            OneBaseInfo.OnlineState = OneUserInfo.OnlineState
#            logging.error( "--------------------- GetOneUserFriendBaseInfoList 2: OneUserInfo.NickName = %s, OneBaseInfo.NickName = %s" % (OneUserInfo.NickName, OneBaseInfo.NickName) )


            FreindInfos.append(OneBaseInfo)


#    logging.error( "--------------------- GetOneUserFriendBaseInfoList 3: FreindInfos number = %d" % (len(FreindInfos)) )
    return FreindInfos, PrePageTag, NextPageTag
        


#添加一个朋友
def AddFriend(FriendLoginName, FriendAllowType, ApplyExplain = ''):
    LoginName = commonfunction.GetUserLoginName()
    if 1 > len(FriendLoginName) or 1 > len(LoginName):
        return

    if 0 != FriendAllowType and 1 != FriendAllowType:
        return

    if FriendLoginName == LoginName:
        return

    FriendItem = GetOneMyFriend(FriendLoginName)
    if FriendItem:
        if 2 == FriendItem.ResponsionState:   #原来被拒绝
            FriendItem.ResponsionState = 0
            FriendItem.put()
        return
            
    #原来不存在该朋友
    NewFriendItem = googledatabase.CFriendTable()
    NewFriendItem.FriendName = FriendLoginName
    NewFriendItem.LoginName = LoginName
    NewFriendItem.ApplyType = 0
    NewFriendItem.ApplyExplain = ApplyExplain
    if FriendAllowType == 0:
        NewFriendItem.ResponsionState = 1
    else:
        NewFriendItem.ResponsionState = 0
        
    NewFriendItem.put()

    #看是否直接为对方添加
    if FriendAllowType == 0:
        OtherFriendItem = GetOneUserFriend(NewFriendItem.LoginName, NewFriendItem.FriendName)
        if OtherFriendItem == None:
            #自动为对方添加自己
            OtherFriendItem = googledatabase.CFriendTable()
            OtherFriendItem.FriendName = NewFriendItem.LoginName
            OtherFriendItem.LoginName = NewFriendItem.FriendName
            OtherFriendItem.ResponsionState = 1
            OtherFriendItem.ApplyType = 1
            OtherFriendItem.ApplyExplain = ''
            OtherFriendItem.put()



#取得申请成为自己朋友的用户列表
def GetApplyMyFriendRecord(TimeDelta):
    LoginName = commonfunction.GetUserLoginName()
    if 1 > len(LoginName):
        return None
    
    Query = db.GqlQuery( 'SELECT * FROM CFriendTable WHERE FriendName = :1 AND ResponsionState = 0 ORDER BY Date', LoginName )
    Results = Query.fetch(1000)

    #修正用户昵称
    for Item in Results:
        Item.LoginName = commonfunction.GetOneUserNickName(Item.LoginName)
        if '' == Item.LoginName:
            Item.LoginName = commonfunction.GetEmptyNickName(TimeDelta)
                
        Item.Date += TimeDelta
        
    return Results


#接受或拒绝一个成为自己朋友的申请
def AcceptOneFriend(FriendLoginName, ResponsionState):
    if 1 != ResponsionState and 2 != ResponsionState:
        return
    
    LoginName = commonfunction.GetUserLoginName()
    FriendItem = GetOneUserFriend(LoginName, FriendLoginName)
    assert FriendItem.FriendName == LoginName
    if FriendItem == None:
        return

    if FriendItem.ResponsionState != 0:
        logging.error("-------AcceptOneFriend FriendItem.ResponsionState != 0, FriendItem.ResponsionState = %d" % (FriendItem.ResponsionState) )
        return

    FriendItem.ResponsionState = ResponsionState
    FriendItem.put()

    if 1 == ResponsionState:
        #复制一份给自己，成为自己的朋友
        NewFriendItem = googledatabase.CFriendTable()
        NewFriendItem.FriendName = FriendItem.LoginName
        NewFriendItem.LoginName = FriendItem.FriendName
        NewFriendItem.ResponsionState = 1
        NewFriendItem.ApplyType = 1
        NewFriendItem.ApplyExplain = ''
        NewFriendItem.put()    


def DeleteOneFriend(FriendLoginName, ResponsionState = -1):
    LoginName = commonfunction.GetUserLoginName()
#    logging.error("-------DeleteOneFriend FriendLoginName = %s, LoginName = %s, ResponsionState = %d" % (FriendLoginName, LoginName, ResponsionState) )
    if 1 > len(FriendLoginName) or 1 > len(LoginName):
        return
    
    Query = db.GqlQuery('SELECT * FROM CFriendTable WHERE FriendName = :1 AND LoginName = :2', FriendLoginName, LoginName)
    if -1 < ResponsionState:
        Query = db.GqlQuery('SELECT * FROM CFriendTable WHERE FriendName = :1 AND LoginName = :2 AND ResponsionState = :3', FriendLoginName, LoginName, ResponsionState)
    
    Results = Query.fetch(1)
#    logging.error("-------DeleteOneFriend Query = %s, Results = %s, Results len = %d" % (Query, Results, len(Results)) )
    
    db.delete(Results)
    

